//
//  RHPlantGroupBatchSendView.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/2/20.
//

#import "RHBatchPlantGroupSendView.h"
#import "RHSearchView.h"
#import "RHBatchPlantGroupSelectCell.h"
#import "KWTPlantGroupModel.h"
#import "RHGolobalSetModel.h"
#import "SYChartTool.h"
#import "KWTMGRNSettingModel.h"
#import "KWT233KSettingModel.h"
#import "RHAlertView.h"
#import "RHChoiceTypeView.h"
#import "RHVppSetCommonModel.h"
#import "JCDataConvert.h"

@interface RHBatchPlantGroupSendView()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *plantGroupListArr;

@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic ,copy) NSString *keyCode;

@property (nonatomic ,strong) UIView *bgView;

@property (nonatomic, strong) MASConstraint *bgv_constraint;

@property (nonatomic, strong) RHSearchView *searchView;

@property (nonatomic, strong) QMUIButton *sendBtn;

@property (nonatomic, strong) QMUIButton *selectBtn;

@property (nonatomic, strong) QMUILabel *selectCountLab;

@property (nonatomic, strong) NSMutableArray *selectedArr;

@property (nonatomic, assign) NSInteger type;//1充电  2放电   3待机

@property (nonatomic, strong) dispatch_group_t group_type;//获取充放电参数

@property (nonatomic, assign) BOOL isFinish;//是否全部下发完成

@property (nonatomic, copy) NSString *errorInfo;//错误信息
@end
@implementation RHBatchPlantGroupSendView
-(instancetype)initWithType:(NSInteger)type
{
    if (self == [super init]) {
        self.type = type;
        [self setupUI];
        self.currentPage = 1;
        self.numOfPage = 10;
        self.requestType = RequestTypeRefresh;
        [self getPlantGroupList];
        [self updateSelectCount];
    }
    return self;
}

- (void)setupUI
{
    self.backgroundColor = UIColor.clearColor;
    self.selectedArr = [NSMutableArray array];
    
    _bgView = kView;
    _bgView.backgroundColor = UIColor.whiteColor;
    _bgView.layer.cornerRadius = 15;
    _bgView.layer.masksToBounds = YES;
     _bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    [self addSubview:_bgView];
    [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
      self.bgv_constraint =  make.top.equalTo(self.mas_bottom).mas_offset(0);
    }];
//    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]init];
//    [_bgView addGestureRecognizer:tapGesture];
    
    kWeakSelf;
    //搜索栏
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 15, kUI_WINDOW_W, 55)];
    [_bgView addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入关键字".rh_localized;
   
    
    UIView *bottomView = kView;
    bottomView.backgroundColor = UIColor.whiteColor;
    [_bgView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.height.offset(44);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    _selectBtn = [QMUIButton buttonWithImage:@"ugrade_cancel"];
    [_selectBtn setImage:[UIImage imageNamed:@"ugrade_select"] forState:UIControlStateSelected];
    [bottomView addSubview:_selectBtn];
    [_selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(25);
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    [_selectBtn addTarget:self action:@selector(selectAll:) forControlEvents:UIControlEventTouchUpInside];
    
    _sendBtn = [[QMUIButton alloc]init];
    [_sendBtn setTitle:@"下发指令".rh_localized forState:UIControlStateNormal];
    [_sendBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [_sendBtn setBackgroundColor:CMainColorGreen];
    [_sendBtn setCornerRadius:8];
    _sendBtn.titleLabel.font = kBOLDSYSTEMFONT(16);
    [_sendBtn.titleLabel sizeToFit];
    CGFloat btnWidth = _sendBtn.titleLabel.width+20;
    [bottomView addSubview:_sendBtn];
    [_sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-15);
        make.height.offset(44);
        make.centerY.mas_offset(0);
        make.width.offset(btnWidth);
    }];
    
    _selectCountLab = [QMUILabel labelWithFont:kSYSTEMFONT(13) textColor:kCOLOR_HEX(@"#3F4443") textAligment:NSTextAlignmentLeft];
    _selectCountLab.text = [NSString stringWithFormat:@"%@%d",@"已选".rh_localized,0];
    [bottomView addSubview:_selectCountLab];
    [_selectCountLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.selectBtn.mas_right).offset(5);
        make.centerY.mas_offset(0);
        make.right.equalTo(weakSelf.sendBtn.mas_left).offset(-5);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.whiteColor];
    [_tableView registerClass:[RHBatchPlantGroupSelectCell class] forCellReuseIdentifier:@"RHBatchPlantGroupSelectCell"];
    [_bgView addSubview:_tableView];
//    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.bottom.equalTo(bottomView.mas_top);
        make.height.offset(6*50);
    }];
   
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
//        weakSelf.keyCode = @"";
        [weakSelf getPlantGroupList];
        //刷新个数
        [weakSelf.selectedArr removeAllObjects];
        [weakSelf updateSelectCount];
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getPlantGroupList];
    }];
    
    UIView *tapView = kView;
    [self addSubview:tapView];
    [tapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.bottom.equalTo(weakSelf.bgView.mas_top);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    [tapView addGestureRecognizer:tap];
    [tap addTarget:self action:@selector(dismiss)];
    
    [[_sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf batchSendAction];
    }];
}
-(void)selectAll:(QMUIButton*)sender
{
    sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        [self.selectedArr removeAllObjects];
        [self.plantGroupListArr enumerateObjectsUsingBlock:^(KWTPlantGroupModel*  _Nonnull plantModel, NSUInteger idx, BOOL * _Nonnull stop) {
            plantModel.isSelected = YES;
            [self.selectedArr addObject:plantModel];
        }];
    }else{
        [self.selectedArr removeAllObjects];
        [self.plantGroupListArr enumerateObjectsUsingBlock:^(KWTPlantGroupModel*  _Nonnull plantModel, NSUInteger idx, BOOL * _Nonnull stop) {
            plantModel.isSelected = NO;
        }];
    }
    [self.tableView reloadData];
    [self updateSelectCount];
}

-(void)updateSelectCount
{
    _selectCountLab.text = [NSString stringWithFormat:@"%@(%ld)",@"已选".rh_localized,self.selectedArr.count];
    if (self.selectedArr.count == self.plantGroupListArr.count) {
        _selectCountLab.text = [NSString stringWithFormat:@"%@(%ld)",@"全选 已选".rh_localized,self.selectedArr.count];
    }
    self.selectBtn.selected = self.selectedArr.count>0;
//    _selectImg.image = [UIImage imageNamed:self.selectedArr.count>0?@"ugrade_select":@"ugrade_cancel"];
    self.sendBtn.enabled = self.selectedArr.count>0;
}

#pragma mark ---------- 获取电站列表 -----------
-(void)getPlantGroupList
{
    
        //获取自己的电站列表
        NSDictionary *para = @{@"pageNum":@(self.currentPage),
                               @"pageSize":@(self.numOfPage),
                               @"groupName":ValidNullData(self.keyCode)
        };
        [QMUITips showLoadingInView:self];
        [KWTPlantGroupModel startGetWithCompletionAPIKey:H_plantGroupList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                NSInteger total = [request.responseObject[@"total"] integerValue];
                self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
                NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
                //下拉刷新
                if(self.requestType == RequestTypeRefresh){
                    [self.tableView endHeaderRefresh];
                    self.plantGroupListArr = arr;
                }else{//上拉加载
                    [self.tableView endFooterRefresh];
                    [self.plantGroupListArr addObjectsFromArray:arr];
                }
                if(self.currentPage >= self.totalPage){
                    [self.tableView endFooterRefreshWithNoMoreData];
                }
                [self.tableView reloadData];
                if(self.plantGroupListArr.count == 0){
                    [self.tableView endFooterRefreshWithNoMoreData];
                }
            }

        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [QMUITips hideAllTips];
            [self.tableView endHeaderRefresh];
        }];
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.plantGroupListArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHBatchPlantGroupSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHBatchPlantGroupSelectCell"];
    cell.model = self.plantGroupListArr[indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    KWTPlantGroupModel *model = self.plantGroupListArr[indexPath.row];
    if (!model.isSelected && model.invType.length == 0) {
        [QMUITips showInfo:@"没有逆变器类型".rh_localized];
        return;
    }
    model.isSelected = !model.isSelected;
    [tableView reloadData];
    if (model.isSelected) {
        if (![self.selectedArr containsObject:model]) {
            [self.selectedArr addObject:model];
        }
    }else{
        [self.selectedArr removeObject:model];
    }
    [self updateSelectCount];
}

#pragma mark ----- 点击批量下发
-(void)batchSendAction
{
    NSString *alertTitle;
    NSString *subTitle;
    if (self.type == 1) {
        alertTitle = @"强制充电指令".rh_localized;
        subTitle = [NSString stringWithFormat:@"确认批量下发强制充电指令到%ld个分组".rh_localized,self.selectedArr.count];
    }
    if (self.type == 2) {
        alertTitle = @"强制放电指令".rh_localized;
        subTitle = [NSString stringWithFormat:@"确认批量下发强制放电指令到%ld个分组".rh_localized,self.selectedArr.count];
    }
    if (self.type == 3) {
        alertTitle = @"待机指令".rh_localized;
        subTitle = [NSString stringWithFormat:@"确认批量下发待机指令到%ld个分组".rh_localized,self.selectedArr.count];
    }
    if (self.type == 4) {
        alertTitle = @"策略指令".rh_localized;
        subTitle = [NSString stringWithFormat:@"确认批量下发策略指令到%ld个分组".rh_localized,self.selectedArr.count];
    }
   
    RHAlertView *alertView = [[RHAlertView alloc]initWithType:RHAlertTypeTipsSubTitle title:alertTitle subTitle:subTitle];
    [alertView.cancelBtn rounded:8 width:1 color:kCOLOR_HEX_A(@"#7E868E",0.24)];
    [alertView.cancelBtn setTitleColor:kCOLOR_HEX_A(@"#171A1D", 0.6) forState:UIControlStateNormal];
    [alertView.sureBtn setBackgroundColor:CMainColorGreen];
    [alertView.sureBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [alertView show];
    kWeakSelf;
    alertView.sureBlock = ^(NSString * _Nonnull content) {
        [weakSelf checkGroupType];
    };
    
   
}

#pragma mark ----- 计算类型个数
-(void)checkGroupType
{
    kWeakSelf;
    self.isFinish = YES;
    self.errorInfo = nil;
    self.group_type = dispatch_group_create();
    
    NSMutableArray *typeArr = [NSMutableArray array];
    [self.selectedArr enumerateObjectsUsingBlock:^(KWTPlantGroupModel*  _Nonnull groupModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![typeArr containsObject:groupModel.invType]&&groupModel.invType.length>0) {
            [typeArr addObject:groupModel.invType];
        }
    }];
    
    
   
    if (typeArr.count>0) {
        //待机,无需查充放电配置参数,soc和功率直接设为0;
        if (self.type == 3) {
            RHGolobalSetModel *standbySetModel = [[RHGolobalSetModel alloc]init];
            standbySetModel.chargeSoc = @"0";
            standbySetModel.dischargeSoc = @"0";
            standbySetModel.power = @"0";
            [typeArr enumerateObjectsUsingBlock:^(NSString*  _Nonnull groupInvType, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([groupInvType isEqualToString:InvType_InvMegarevoLv12KW]) {
                    dispatch_group_enter(weakSelf.group_type);
                    [weakSelf s40kChgActionWithType:weakSelf.type configModel:standbySetModel];
                }else if ([groupInvType isEqualToString:InvType_PCS_BCS_B_HM_USX2]) {
                   
                    dispatch_group_enter(weakSelf.group_type);
                    [weakSelf me233ChgActionWithType:weakSelf.type configModel:standbySetModel];
                }else if ([groupInvType isEqualToString:InvType_Sol_Ark_30K_3P_208V]||
                          [groupInvType isEqualToString:InvType_Sol_Ark_60K_3P_480V]) {
                    
                    dispatch_group_enter(weakSelf.group_type);
                    [weakSelf meSolarkChgActionWithType:weakSelf.type configModel:standbySetModel chargeType:@"0"];
                }else if ([groupInvType isEqualToString:InvType_InvHISOLAR15KW]) {
                    
                    dispatch_group_enter(weakSelf.group_type);
                    [weakSelf HiSolarkChgActionWithType:weakSelf.type configModel:standbySetModel];
                }
            }];
        }else if(self.type == 4){
            //读取策略配置
            [typeArr enumerateObjectsUsingBlock:^(NSString*  _Nonnull groupInvType, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([groupInvType isEqualToString:InvType_InvMegarevoLv12KW]) {
                    dispatch_group_enter(weakSelf.group_type);
                    [weakSelf getPolicyParaConfig:3];
                }else if ([groupInvType isEqualToString:InvType_PCS_BCS_B_HM_USX2]) {
                   
                    dispatch_group_enter(weakSelf.group_type);
                    [weakSelf getPolicyParaConfig:2];
                }else if ([groupInvType isEqualToString:InvType_Sol_Ark_30K_3P_208V]) {
                   
                    dispatch_group_enter(weakSelf.group_type);
                    [weakSelf getPolicyParaConfig:4];
                }else if ([groupInvType isEqualToString:InvType_Sol_Ark_60K_3P_480V]) {
                   
                    dispatch_group_enter(weakSelf.group_type);
                    [weakSelf getPolicyParaConfig:5];
                }else if ([groupInvType isEqual:InvType_InvHISOLAR15KW]) {
                    
                    dispatch_group_enter(weakSelf.group_type);
                    [weakSelf getPolicyParaConfig:7];
                }
            }];
        }
        
        else{
            dispatch_group_enter(self.group_type);
            
            //查询充放电配置参数   1和2(充电和放电)
            //如果包含 solark 逆变器分组,要选择是电网充电还是发电机充电
            if ([typeArr containsObject:InvType_Sol_Ark_30K_3P_208V]||
                [typeArr containsObject:InvType_Sol_Ark_60K_3P_480V]) {
                if (self.type == 1) {//充电
//                    RHChoiceTypeView *choiceView = [[RHChoiceTypeView alloc]init];
//                    choiceView.titleLab.text = @"分组中包含so-ark逆变器,请确认so-ark充电方式!".rh_localized;
//                    choiceView.typeList = @[@"电网充电",@"发电机充电"];
//                    kWeakSelf;
//                    choiceView.choiceResultBlock = ^(NSString * _Nonnull type) {
//                        NSString *chargeType = [type isEqualToString:@"电网充电"]?@"1":@"2";
//                        [weakSelf getplantGroupGolobalConfig:typeArr solarkChargeType:chargeType];
//                    };
//                    [choiceView showAnimation];
                    
                    //改为默认电网充电,不用选择
                    [weakSelf getplantGroupGolobalConfig:typeArr solarkChargeType:@"1"];
                }else  if (self.type == 2){
                    //放电
                    [self getplantGroupGolobalConfig:typeArr solarkChargeType:@"3"];
                }
            }else{
                [self getplantGroupGolobalConfig:typeArr solarkChargeType:@""];
            }
            
        }
        
    }else{
        [QMUITips showInfo:@"不支持".rh_localized];
        return;
    }
    //获取完充放电配置参数
    NSLog(@"分组类型-----%@",typeArr);
    dispatch_group_notify(self.group_type, dispatch_get_main_queue(), ^{
        if (self.isFinish) {
            NSLog(@"---->全部下发完成");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [QMUITips showSucceed:@"设置完成".rh_localized inView:self hideAfterDelay:1];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self dismiss];
                });
            });
        }else{
            if (self.errorInfo) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [QMUITips showInfo:self.errorInfo];
                   
                });
            }
        }
    });
}



#pragma mark ----- 获取强制充放一键配置(待机无需获取,直接设成0)
-(void)getplantGroupGolobalConfig:(NSArray*)groupTypeArr solarkChargeType:(NSString*)solarkChargeType
{
    [QMUITips showLoadingInView:kAppWindow];
    kWeakSelf;
    
    
    [RHGolobalSetModel startGetWithCompletionAPIKey:H_getPlantGroupForceConfig argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        if (resultModel.code == 200) {
            NSDictionary *dataDic = request.responseJSONObject[@"data"];
            [groupTypeArr enumerateObjectsUsingBlock:^(NSString*  _Nonnull groupInvType, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([groupInvType isEqualToString:InvType_InvMegarevoLv12KW]) {
                    if (dataDic[groupInvType]) {
                        RHGolobalSetModel *s40Model = [RHGolobalSetModel yy_modelWithJSON:dataDic[groupInvType]];
                        dispatch_group_enter(weakSelf.group_type);
                        NSLog(@"----->进组1");
                        [weakSelf s40kChgActionWithType:weakSelf.type configModel:s40Model];
                    }else{
                        [QMUITips showInfo:@"请先配置充放电参数".rh_localized];
                    }
                   
                }else if ([groupInvType isEqualToString:InvType_PCS_BCS_B_HM_USX2]) {
                    if (dataDic[groupInvType]) {
                        RHGolobalSetModel *r233Model = [RHGolobalSetModel yy_modelWithJSON:dataDic[groupInvType]];
                        dispatch_group_enter(weakSelf.group_type);
                        NSLog(@"----->进组2");
                        [weakSelf me233ChgActionWithType:weakSelf.type configModel:r233Model];
                    }else{
                        [QMUITips showInfo:@"请先配置充放电参数".rh_localized];
                    }
                   
                }else if ([groupInvType isEqualToString:InvType_Sol_Ark_30K_3P_208V]||
                          [groupInvType isEqualToString:InvType_Sol_Ark_60K_3P_480V]) { //61度电 solark逆变器
                    if (dataDic[groupInvType]) {
                        RHGolobalSetModel *solarkModel = [RHGolobalSetModel yy_modelWithJSON:dataDic[groupInvType]];
                        dispatch_group_enter(weakSelf.group_type);
                        NSLog(@"----->进组2");
                        
                        [weakSelf meSolarkChgActionWithType:weakSelf.type configModel:solarkModel chargeType:solarkChargeType];
                    }else{
                        [QMUITips showInfo:@"请先配置充放电参数".rh_localized];
                    }
                   
                }else if ([groupInvType isEqualToString:InvType_InvHISOLAR15KW]) { //储充一体 hisolark逆变器
                    if (dataDic[groupInvType]) {
                        RHGolobalSetModel *hisolarkModel = [RHGolobalSetModel yy_modelWithJSON:dataDic[groupInvType]];
                        dispatch_group_enter(weakSelf.group_type);
                        NSLog(@"----->进组3");
                        
                        [weakSelf HiSolarkChgActionWithType:weakSelf.type configModel:hisolarkModel];
                    }else{
                        [QMUITips showInfo:@"请先配置充放电参数".rh_localized];
                    }
                   
                }
            }];
            dispatch_group_leave(self.group_type);
        }
       
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}

#pragma mark ---- 获取策略配置(通用233,s40K,solark)
//1:强制充放电  2:通用  3:s40K 4:solark 7:hisolark
-(void)getPolicyParaConfig:(NSInteger)configType
{
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startGetWithCompletionAPIKey:H_getPlantGroupForceConfig argument:@{@"configType":@(configType)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {

        if (resultModel.code == 200) {
            NSDictionary *dataDic = request.responseJSONObject[@"data"];
            if (dataDic[@"strategy"]) {
                NSDictionary *dic = [dataDic[@"strategy"] jsonStringToDictionary];
                
                if(dic[@"protocolBody"]){
                    NSArray *paraArr = dic[@"protocolBody"][@"commandParamList"];
                   //参数批量下发
                    [self batchPolicyParaSendWith:configType paraList:paraArr];
                }else{
                    dispatch_group_leave(self.group_type);
                    self.isFinish = NO;
                    self.errorInfo = @"没有配置参数".rh_localized;
                    NSLog(@"---->没有配置 %@ 参数",configType == 2?@"通用策略":@"s40k");
                }
                
            }else{
                dispatch_group_leave(self.group_type);
                self.isFinish = NO;
                self.errorInfo = @"没有配置参数".rh_localized;
                NSLog(@"---->没有配置 %@ 参数",configType == 2?@"通用策略":@"s40k");
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        dispatch_group_leave(self.group_type);
        self.isFinish = NO;
        self.errorInfo = @"没有配置参数".rh_localized;
    }];
    
   
}

#pragma mark -------s40K 1强制充电  2强制放电 3待机
-(void)s40kChgActionWithType:(NSInteger)type configModel:(RHGolobalSetModel*)configModel
{
//    if ([model.plantCount integerValue] == 0) {
//        [QMUITips showInfo:@"请添加电站".rh_localized];
//        return;
//    }
  
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_ao_mgrn_chg"];
    NSArray *modelArr = [NSArray yy_modelArrayWithClass:[KWTMGRNSettingModel class] json:arr];
    
    NSMutableArray *paraArr = [NSMutableArray array];
    NSDictionary *modeDic = @{
        @"paramName": @"Inv3_AdvaMode",
        @"regAddr" : @(1067),
        @"offset" : @(0),
        @"num" : @(16),
        @"dataType" : @"int",
        @"value" : @"1"

    };

    NSDictionary *touDic = @{
        @"paramName": @"Inv3_TOUEn",
        @"regAddr" : @(1069),
        @"offset" : @(4),
        @"num" : @(1),
        @"dataType" : @"int",
        @"value" : @"1"

    };
    [paraArr addObject:modeDic];
    [paraArr addObject:touDic];
    [modelArr enumerateObjectsUsingBlock:^(KWTMGRNSettingModel*  _Nonnull sectionModel, NSUInteger sectionIdx, BOOL * _Nonnull stop) {
        [sectionModel.rows enumerateObjectsUsingBlock:^(KWTMGRNSettingModel*  _Nonnull rowModel, NSUInteger rowIdx, BOOL * _Nonnull stop) {
            if (![rowModel.type isEqualToString:@"time"]) {//只处理时间设置
                return;
            }
            [rowModel.items enumerateObjectsUsingBlock:^(KWTMGRNSettingModel * _Nonnull itemModel, NSUInteger itemIdx, BOOL * _Nonnull stop) {
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:itemModel.format forKey:@"dataType"];
                [textDic setObject:itemModel.key forKey:@"paramName"];
                
                [textDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(itemModel.num) forKey:@"num"];
                [textDic setObject:@(itemModel.offset) forKey:@"offset"];
                
                NSString *ts_key = [NSString stringWithFormat:@"Inv3_TS%zd",rowIdx+1];
                NSString *td_key = [NSString stringWithFormat:@"Inv3_TD%zd",rowIdx+1];
                NSString *soc_key = [NSString stringWithFormat:@"Inv3_TSoc%zd",rowIdx+1];
                NSString *power_key = [NSString stringWithFormat:@"Inv3_TPo%zd",rowIdx+1];
                NSString *chg_key = [NSString stringWithFormat:@"Inv3_T%zdEn",rowIdx+1];
                NSString *dchg_key = [NSString stringWithFormat:@"Inv3_Gen%zdEn",rowIdx+1];
                if ([itemModel.key isEqualToString:ts_key]) {
                    [textDic setObject:@"0000" forKey:@"value"];
                }
                if ([itemModel.key isEqualToString:td_key]) {//时段1以下的都设成0
                    [textDic setObject:rowIdx==0?@"2359":@"0000" forKey:@"value"];
                    
                }
                
                if ([itemModel.key isEqualToString:soc_key]) {
                    NSString *soc = type == 1?ValidNullData(configModel.chargeSoc):ValidNullData(configModel.dischargeSoc);
                    if (rowIdx>0) {
                        soc = @"0";
                    }
                    //待机 soc设为0
                    if(type ==3){
                        soc = @"0";
                    }
                    [textDic setObject:soc forKey:@"value"];
                }
                
                if ([itemModel.key isEqualToString:power_key]) {
                    NSString *power = ValidNullData(configModel.power);
                    
                    if ([configModel.power integerValue]>30000) {
                        power = @"30000";
                    }
                    if (rowIdx > 0) {
                        power = @"0";
                    }
                    //待机 功率设为0
                    if(type ==3){
                        power = @"0";
                    }
                    [textDic setObject:power forKey:@"value"];
                }
                
                if ([itemModel.key isEqualToString:chg_key]) {//充电使能
                    [textDic setObject:type==1?@"1":@"0" forKey:@"value"];
                    if (type == 3) {//待机时,使能设为0
                        [textDic setObject:@"0" forKey:@"value"];
                    }
                }
                
                if ([itemModel.key isEqualToString:dchg_key]) {//放电使能
                    [textDic setObject:type==1?@"0":@"1" forKey:@"value"];
                    if (type == 3) {
                        [textDic setObject:@"0" forKey:@"value"];
                    }
                }
                [paraArr addObject:textDic];
            }];
        }];
    }];
    
    
    //参数组装完
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //分组id
    NSMutableArray *s40KArray = [NSMutableArray array];
   
    [self.selectedArr enumerateObjectsUsingBlock:^(KWTPlantGroupModel*  _Nonnull groupModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([groupModel.type isEqualToString:@"S40K LV1.0"]) {
            [s40KArray addObject:@(groupModel.groupId)];
        }
    }];
    [requestPara setObject:s40KArray forKey:@"ids"];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    //全部参数一次性给到后台 , 不需要填端点sn参数,因为获取不到
    [paraListArr addObjectsFromArray:paraArr];

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
       
        @"paramCount":@(paraListArr.count),
       
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:kApplication.keyWindow];
    [BaseModel startWithCompletionAPIKey:H_batchGroupVppSet argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
        if (resultModel.code == 200) {
            
        }else{
            self.isFinish = NO;
            self.errorInfo = resultModel.message;
        }
        
        dispatch_group_leave(self.group_type);
       
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        self.isFinish = NO;
        dispatch_group_leave(self.group_type);
    }];
}

#pragma mark -------233 1强制充电  2强制放电 3待机
-(void)me233ChgActionWithType:(NSInteger)type configModel:(RHGolobalSetModel*)configModel
{
//    if ([model.plantCount integerValue] == 0) {
//        [QMUITips showInfo:@"请添加电站".rh_localized];
//        return;
//    }
    
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_me_233_vpp_set"];
    NSArray *modelArr = [NSArray yy_modelArrayWithClass:[KWT233KSettingModel class] json:arr];
    
    //生成24个时间
    NSMutableArray *rowArr = [NSMutableArray array];
    [modelArr enumerateObjectsUsingBlock:^(KWT233KSettingModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([sectionModel.type isEqualToString:@"time"]) {
            KWT233KSettingModel *rowModel = [sectionModel.rows firstObject];
            KWT233KSettingModel *socModel = [rowModel.items safeObjectAtIndex:1];
            KWT233KSettingModel *powerModel = [rowModel.items safeObjectAtIndex:2];
            for (int i = 0; i <24; i++) {
                KWT233KSettingModel *rowNewModel = [[KWT233KSettingModel alloc]init];
                rowNewModel.type = rowModel.type;
                rowNewModel.comment = [NSString stringWithFormat:@"%02d:00-%02d:00",i,i+1];
                
                NSMutableArray *items = [NSMutableArray array];

                KWT233KSettingModel *socNewModel = [[KWT233KSettingModel alloc]init];
                socNewModel.key     = [NSString stringWithFormat:@"%@%d",socModel.key,i+1];
                socNewModel.format  = socModel.format;
                socNewModel.type    = socModel.type;
                socNewModel.regAddr = socModel.regAddr + i;
                socNewModel.offset  = socModel.offset;
                socNewModel.num     = socModel.num;
                KWT233KSettingModel *powerNewModel = [[KWT233KSettingModel alloc]init];
                powerNewModel.key     = [NSString stringWithFormat:@"%@%d",powerModel.key,i+1];
                powerNewModel.format  = powerModel.format;
                powerNewModel.type    = powerModel.type;
                powerNewModel.regAddr = powerModel.regAddr + i;
                powerNewModel.offset  = powerModel.offset;
                powerNewModel.num     = powerModel.num;
//                [items addObject:chgTagNewModel];
                [items addObject:socNewModel];
                [items addObject:powerNewModel];
                rowNewModel.items = items.copy;
                [rowArr addObject:rowNewModel];
            }
            sectionModel.rows = rowArr.copy;
        }
    }];
    
    
    NSMutableArray *paraArr = [NSMutableArray array];
    [modelArr enumerateObjectsUsingBlock:^(KWT233KSettingModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [sectionModel.rows enumerateObjectsUsingBlock:^(KWT233KSettingModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            //系统设置不提交(单独提交)
            if ([rowModel.type isEqualToString:@"date"]) {
                return;
            }
            //工作模式
            if ([rowModel.type isEqualToString:@"switch"]||[rowModel.type isEqualToString:@"select"]) {
                if (rowModel.content.length == 0) {
                    return;
                }
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:rowModel.format forKey:@"dataType"];
                [textDic setObject:rowModel.key forKey:@"paramName"];
                [textDic setObject:rowModel.content forKey:@"value"];//默认削峰填谷
                [textDic setObject:@(rowModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(rowModel.num) forKey:@"num"];
                [textDic setObject:@(rowModel.offset) forKey:@"offset"];
                if (type==3) {
                    [textDic setObject:@"0" forKey:@"value"];//待机
                }
                [paraArr addObject:textDic];
            }
            
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {
               
                [rowModel.items enumerateObjectsUsingBlock:^(KWT233KSettingModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (itemModel.key.length == 0) {//充放电字段不提交
                        return;
                    }
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
//                    [itemDic setObject:itemModel.content forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    
                    if ([itemModel.key containsString:@"Emu_EndSocSeg"]) {//SOC
                        NSString *socValue = type == 1?configModel.chargeSoc:configModel.dischargeSoc;
                        [itemDic setObject:socValue forKey:@"value"];
                        if(type == 3){//待机
                            [itemDic setObject:@"0" forKey:@"value"];
                        }
                    }
                    //功率值要根所充放电状态来发送正负值
                    if ([itemModel.key containsString:@"Emu_PwrSeg"]) {//功率
                        NSString *value = configModel.power;
                        if ([value integerValue]>125) {//最大功率100KW
                            value = @"125";
                        }
                        if (type == 1) {//充电发负数
                            if (![value containsString:@"-"]) {
                                NSString *dchg = [NSString stringWithFormat:@"-%@",value];
                                [itemDic setObject:dchg forKey:@"value"];
                            }
                        }
                        if (type == 2) {//放电发正数
                            [itemDic setObject:value forKey:@"value"];
                        }
                        
                        if (type == 3) {//待机
                            [itemDic setObject:@"0" forKey:@"value"];
                        }
                    }
                    [paraArr addObject:itemDic];
                }];
            }
            
        }];
        
    }];
    
    //组装好参数后
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //分组id
    NSMutableArray *r233Array = [NSMutableArray array];
    [self.selectedArr enumerateObjectsUsingBlock:^(KWTPlantGroupModel*  _Nonnull groupModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([groupModel.type is233DeviceType]) {
            [r233Array addObject:@(groupModel.groupId)];
        }
    }];
    [requestPara setObject:r233Array forKey:@"ids"];
    
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    //全部参数一次性给到后台 , 不需要填端点sn参数,因为获取不到
    [paraListArr addObjectsFromArray:paraArr];

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"paramCount":@(paraListArr.count),
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:kApplication.keyWindow];

    [BaseModel startWithCompletionAPIKey:H_batchGroupVppSet argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        if (resultModel.code == 200) {

        }else{
            self.isFinish = NO;
            self.errorInfo = resultModel.message;
        }
        
        dispatch_group_leave(self.group_type);

    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        self.isFinish = NO;
        dispatch_group_leave(self.group_type);
    }];
}

#pragma mark -------61度电 solark逆变器 1强制充电  2强制放电 3待机
-(void)meSolarkChgActionWithType:(NSInteger)type configModel:(RHGolobalSetModel*)configModel chargeType:(NSString*)chargeType
{
//    if ([model.plantCount integerValue] == 0) {
//        [QMUITips showInfo:@"请添加电站".rh_localized];
//        return;
//    }
    
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_me_solark_vpp_set"];
    NSArray *modelArr = [NSArray yy_modelArrayWithClass:[KWT233KSettingModel class] json:arr];
    
    NSMutableArray *paraArr = [NSMutableArray array];
    [modelArr enumerateObjectsUsingBlock:^(KWT233KSettingModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [sectionModel.rows enumerateObjectsUsingBlock:^(KWT233KSettingModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            //系统设置不提交(单独提交)
            if ([rowModel.type isEqualToString:@"date"]) {
                return;
            }
            //工作模式
            if ([rowModel.type isEqualToString:@"switch"]||[rowModel.type isEqualToString:@"select"]) {
                if (rowModel.content.length == 0) {
                    return;
                }
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:rowModel.format forKey:@"dataType"];
                [textDic setObject:rowModel.key forKey:@"paramName"];
                [textDic setObject:rowModel.content forKey:@"value"];//默认削峰填谷
                [textDic setObject:@(rowModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(rowModel.num) forKey:@"num"];
                [textDic setObject:@(rowModel.offset) forKey:@"offset"];
                if (type==3) {
                    [textDic setObject:@"0" forKey:@"value"];//待机
                }
                [paraArr addObject:textDic];
            }
            
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {
               
                [rowModel.items enumerateObjectsUsingBlock:^(KWT233KSettingModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (itemModel.key.length == 0) {//充放电字段不提交
                        return;
                    }
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:ValidNullDataToString(itemModel.content, @"0") forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    
                    //TOU_Time_1_Battery_Cut_Off_SOC
                    if ([itemModel.key containsString:@"_Battery_Cut_Off_SOC"]) {//SOC
                        NSString *socValue = type == 1?configModel.chargeSoc:configModel.dischargeSoc;
                        [itemDic setObject:socValue forKey:@"value"];
                        if(type == 3){//待机
                            [itemDic setObject:@"10" forKey:@"value"];
                        }
                    }
                    //功率值要根所充放电状态来发送正负值   TOU_Time_1_Battery_Power
                    if ([itemModel.key containsString:@"_Battery_Power"]) {//功率
                        NSString *value = configModel.power;
                        if ([value integerValue]>60) {//最大功率60KW
                            value = @"60";
                        }
                        if (type == 3) {//待机  功率设为0
                            [itemDic setObject:@"0" forKey:@"value"];
                        }else{
                            [itemDic setObject:value forKey:@"value"];
                        }
                    }
                    //充放电选择项,已在前面作了处理
                    if ([itemModel.key containsString:@"_Charge_Dischange_Selection"]) {
                        [itemDic setObject:chargeType forKey:@"value"];
                    }
                    [paraArr addObject:itemDic];
                }];
            }
            
        }];
        
    }];
    
    //组装好参数后
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //分组id
    NSMutableArray *solarkArray = [NSMutableArray array];
    [self.selectedArr enumerateObjectsUsingBlock:^(KWTPlantGroupModel*  _Nonnull groupModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([groupModel.type is61DeviceType]) {
            [solarkArray addObject:@(groupModel.groupId)];
        }
    }];
    [requestPara setObject:solarkArray forKey:@"ids"];
    
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    //全部参数一次性给到后台 , 不需要填端点sn参数,因为获取不到
    [paraListArr addObjectsFromArray:paraArr];

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    [self forceActionParamSend:requestPara paraListArr:paraListArr];
    
}

#pragma mark -------储充一体机 hisolark逆变器 1强制充电  2强制放电 3待机
-(void)HiSolarkChgActionWithType:(NSInteger)type configModel:(RHGolobalSetModel*)configModel
{

    
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_ao_HiSolar_chg"];
    NSArray *modelArr = [NSArray yy_modelArrayWithClass:[RHVppSetCommonModel class] json:arr];
    
    NSMutableArray *paraArr = [NSMutableArray array];
    
    //工作模式 0:自发自用 1:备电模式 2:PV全额上网模式 3:PV+Bat全额上网模式 4:VPP模式 5:TOU模式
    NSDictionary *modeDic = @{
        @"paramName": @"Inv5_Mode",
        @"regAddr" : @(4203),
        @"offset" : @(0),
        @"num" : @(16),
        @"dataType" : @"int",
        @"value" : @"4"

    };
    [paraArr addObject:modeDic];
    
    //充电使能和放电使能的值,要将使能值组合成一个参数下发
    NSMutableString *enableValue = [NSMutableString string];
    
    [modelArr enumerateObjectsUsingBlock:^(RHVppSetCommonModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [sectionModel.rows enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull rowModel, NSUInteger row_idx, BOOL * _Nonnull stop) {
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {
               
                [rowModel.items enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                   
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:ValidNullDataToString(itemModel.content, @"0") forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    
                    
                    NSString *ts_key = [NSString stringWithFormat:@"Inv5_VTS%zd",row_idx+1];
                    NSString *td_key = [NSString stringWithFormat:@"Inv5_VTE%zd",row_idx+1];
                    NSString *soc_key = [NSString stringWithFormat:@"Inv5_VS%zd",row_idx+1];
                    NSString *power_key = [NSString stringWithFormat:@"Inv5_VP%zd",row_idx+1];
                    NSString *chg_key = [NSString stringWithFormat:@"Inv5_VM%zd",row_idx+1];
                    
                    if ([itemModel.key isEqualToString:ts_key]) {
                        [itemDic setObject:@"0000" forKey:@"value"];
                    }
                    if ([itemModel.key isEqualToString:td_key]) {//时段1以下的都设成0
                        [itemDic setObject:row_idx==0?@"2359":@"0000" forKey:@"value"];
                        if(type == 3){//待机
                            [itemDic setObject:@"0000" forKey:@"value"];
                        }
                    }
               
                    if ([itemModel.key isEqualToString:soc_key]) {//SOC
                        NSString *socValue = type == 1?configModel.chargeSoc:configModel.dischargeSoc;
                        [itemDic setObject:socValue forKey:@"value"];
                        //待机,强制充放电的时候,除第一个时间段,其他的都设为0
                        if(type == 3 || row_idx != 0){
                            [itemDic setObject:@"0" forKey:@"value"];
                        }
                    }
                
                    if ([itemModel.key isEqualToString:power_key]) {//功率
                        NSString *value = configModel.power;
                        if ([value integerValue]>[itemModel.maxValue integerValue]) {//最大功率60KW
                            value = itemModel.maxValue;
                        }
                        //待机  功率设为0  ,强制充放电的时候,除第一个时间段,其他的都设为0
                        if (type == 3 || row_idx != 0) {
                            [itemDic setObject:@"0" forKey:@"value"];
                        }else{
                            [itemDic setObject:value forKey:@"value"];
                        }
                    }
                    //判断放电 = 1 ,其他的设成0
                    if ([itemModel.key isEqualToString:chg_key]) {
                        NSString *value = @"0";
                         value = type==2?@"1":@"0";
                        if (type == 3) {
                            value = @"1";
                        }
                        [itemDic setObject:value forKey:@"value"];
                        //组合所有使能使能
                        [enableValue insertString:value atIndex:0];
                        return;
                        
                    }
                    [paraArr addObject:itemDic];
                }];
            }
            
        }];
        
    }];
    
    //组全使能参数
    NSInteger decimalValue = [JCDataConvert ConvertBinaryStringToDecimal:enableValue];
    NSString *value = [NSString stringWithFormat:@"%ld",decimalValue];
    NSDictionary *enableDic = @{
        @"dataType":@"int",
        @"paramName":@"Inv5_VM",
        @"value":value,
        @"regAddr":@(7224),
        @"num":@(16),
        @"offset":@(0),
    };
    [paraArr addObject:enableDic];
    
    //要按寄存器从小到大排列下发
    [paraArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        if (obj1[@"regAddr"]&&obj2[@"regAddr"]) {
            if ([obj1[@"regAddr"] integerValue] < [obj2[@"regAddr"] integerValue]) {
                return NSOrderedAscending;
            }else if ([obj1[@"regAddr"] integerValue] > [obj2[@"regAddr"] integerValue]){
                return NSOrderedDescending;
            }else{
                return NSOrderedSame;
            }
            
        }else{
            return NSOrderedSame;
        }
    }];
    
    //组装好参数后
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //分组id
    NSMutableArray *solarkArray = [NSMutableArray array];
    [self.selectedArr enumerateObjectsUsingBlock:^(KWTPlantGroupModel*  _Nonnull groupModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([groupModel.type isXStack]) {
            [solarkArray addObject:@(groupModel.groupId)];
        }
    }];
    [requestPara setObject:solarkArray forKey:@"ids"];
    
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    //全部参数一次性给到后台 , 不需要填端点sn参数,因为获取不到
    [paraListArr addObjectsFromArray:paraArr];

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    [self forceActionParamSend:requestPara paraListArr:paraListArr];
    
}

#pragma mark ------  强制充放电参数下发
-(void)forceActionParamSend:(NSMutableDictionary*)requestPara  paraListArr:(NSArray*)paraListArr
{
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"paramCount":@(paraListArr.count),
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:kApplication.keyWindow];

    [BaseModel startWithCompletionAPIKey:H_batchGroupVppSet argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        if (resultModel.code == 200) {

        }else{
            self.isFinish = NO;
            self.errorInfo = resultModel.message;
        }
        
        dispatch_group_leave(self.group_type);

    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        self.isFinish = NO;
        dispatch_group_leave(self.group_type);
    }];
}


#pragma mark ------ 批量策略下发 configType 1:强制充放电  2:通用  3:s40K 4:solark
-(void)batchPolicyParaSendWith:(NSInteger)configType paraList:(NSArray*)paraList
{
    
    NSMutableArray *paraArr = [NSMutableArray array];

    //加入获取到的策略配置参数 (已包含工作模式 参数)
    [paraArr addObjectsFromArray:paraList];
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //分组id
    NSMutableArray *idsArr = [NSMutableArray array];
    
    [self.selectedArr enumerateObjectsUsingBlock:^(KWTPlantGroupModel*  _Nonnull groupModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([groupModel.invType isEqualToString:InvType_InvMegarevoLv12KW]&&(configType == 3)) {
            [idsArr addObject:@(groupModel.groupId)];
        }else if ([groupModel.invType isEqualToString:InvType_PCS_BCS_B_HM_USX2]&&(configType == 2)){
            [idsArr addObject:@(groupModel.groupId)];
        }else if ([groupModel.invType isEqualToString:InvType_Sol_Ark_30K_3P_208V]&&(configType == 4)){
            [idsArr addObject:@(groupModel.groupId)];
        }else if ([groupModel.invType isEqualToString:InvType_Sol_Ark_60K_3P_480V]&&(configType == 5)){
            [idsArr addObject:@(groupModel.groupId)];
        }else if ([groupModel.invType isEqualToString:InvType_InvHISOLAR15KW]&&(configType == 7)){
            [idsArr addObject:@(groupModel.groupId)];
        }
    }];
   
    [requestPara setObject:idsArr forKey:@"ids"];
   
   
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    //全部参数一次性给到后台 , 不需要填端点sn参数,因为获取不到
    [paraListArr addObjectsFromArray:paraArr];

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
       
        @"paramCount":@(paraListArr.count),
       
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:kApplication.keyWindow];
    [BaseModel startWithCompletionAPIKey:H_batchGroupVppSet argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
        if (resultModel.code == 200) {
            
        }else{
            self.isFinish = NO;
            self.errorInfo = resultModel.message;
        }
        dispatch_group_leave(self.group_type);
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        self.isFinish = NO;
        dispatch_group_leave(self.group_type);
    }];
}


-(void)show
{
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
    [kAppWindow.rootViewController.view addSubview:self];
    self.frame = kAppWindow.bounds;
   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.bgv_constraint uninstall];
        
        [self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
          self.bgv_constraint =  make.bottom.mas_offset(0);
         
        }];
        [UIView animateWithDuration:0.3 animations:^{
            self.backgroundColor = kCOLOR_HEX_A(@"000000", 0.4);
            [self setNeedsLayout];
            [self layoutIfNeeded];
        }];
        
    });
}

-(void)dismiss
{
    [self.bgv_constraint uninstall];
    [self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
      self.bgv_constraint =  make.top.equalTo(self.mas_bottom).mas_offset(0);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = kCOLOR_HEX_A(@"000000", 0.4);
        [self setNeedsLayout];
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark ------- textField delegate
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.keyCode = textField.text;
    [self getPlantGroupList];
}


- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    self.keyCode = @"";
    [self getPlantGroupList];
    return YES;
}

-(void)dealloc
{
    NSLog(@"%s",__func__);
}
@end
